/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.LoanverificationDAO;
import com.cashmate.hibernate.pojo.Loanverification;
import com.cashmate.hibernate.pojo.Usertypes;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Dine
 */
public class GridLoanappliSaved extends ActionSupport {

    private static Logger logger = Logger.getLogger(GridLoanappli.class);
    //Your result List
    private List<Loanverification> gridModel;
    //get how many rows we want to have into the grid - rowNum attribute in the grid
    private Integer rows = 0;
    //Get the requested page. By default grid sets this to 1.
    private Integer page = 0;
    // sorting order - asc or desc
    private String sord;
    // get index row - i.e. user click to sort.
    private String sidx;
    // Search Field
    private String searchField;
    // The Search String
    private String searchString;
    // he Search Operation ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
    private String searchOper;
    // Your Total Pages
    private Integer total = 0;
    // All Record
    private Integer records = 0;
    private LoanverificationDAO loanappdao = (LoanverificationDAO) ServletActionContext.getServletContext().getAttribute("loanverificationDAO");
    private Usertypes ut = (Usertypes) ServletActionContext.getRequest().getSession().getAttribute("usertype");

    @Action(value = "/grid-loanappli-saved", results = {
        @Result(name = "success", type = "json"),
        @Result(name = "error", location = "../error/messages.jsp")
    })
    @Override
    public String execute() {
        try {
            //max record
            int to = (rows * page);
            //offset record
            int from = to - rows;

            //Create a Criteria Query for a POJO class (Loanapplications)
            DetachedCriteria criteria = criteria = DetachedCriteria.forClass(Loanverification.class);
            //Join the foreign keyed POJO employees, give it an alias of "e" (line 17 Loanapplications.java)
            // These pojos are not nullables so it is ok to join them already...
            //Criteria.DISTINCT_ROOT_ENTITY means that Loanapplications which is the root entity must be distinct on all joins.
            criteria.createCriteria("employees", "e").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            //Quote Line 67,68
            criteria.createCriteria("documents", "d").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            //Quote Line 67,68
            criteria.createCriteria("borrowers", "bo").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            //Quote Line 67,68
            criteria.createCriteria("bo.branches", "boBra").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            criteria.createCriteria("bo.areas", "boAr").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            //Quote Line 67,68
//            criteria.createCriteria("branches", "b").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            boolean requestJoined = false;
            //set criteria search restrictions
//            if (searchField != null && searchField.length() > 0) {
//                if (searchField.equals("borrowerCode")) {
//                    String brRegex = Utils.segregate("letters", searchString);
//                    criteria.add(Restrictions.like("boBra.branchcode", "%" + brRegex + "%"));
//                    String numbers = Utils.segregate("numbers", searchString);
//                    if (numbers != null && numbers.length() > 0) {
//                        int boroRegex = Integer.parseInt(numbers);
//                        criteria.add(Restrictions.like("bo.borrowerid", boroRegex));
//                    }
//                } else if (searchField.equals("idnumber")) {
//                    criteria.add(Restrictions.like("e.idnumber", "%" + searchString + "%"));
//                } else if (searchField.equals("borrowername")) {
//                    criteria.add(Restrictions.like("bo.completename", "%" + searchString + "%"));
//                } else if (searchField.equals("requestDocumentNo")) {
//                    criteria.createCriteria("request").createCriteria("documents", "reqDoc").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
//                    criteria.add(Restrictions.like("reqDoc.documentno", "%" + searchString + "%"));
//                    requestJoined = true;
//                } else if (searchField.equals("documentno")) {
//                    criteria.add(Restrictions.like("d.documentno", "%" + searchString + "%"));
//                } else if (searchField.equals("suggestedamount") || searchField.equals("amortizationindays")) {
//                    try {
//                        criteria.add(Restrictions.like(searchField, Integer.parseInt(searchString)));
//                    } catch (NumberFormatException nfe) {
//                    }
//                } else if (searchField.equals("amountrequested")) {
//                    try {
//                        criteria.add(Restrictions.like(searchField, Double.parseDouble(searchString)));
//                    } catch (NumberFormatException nfe) {
//                    }
//                } else {
//                    criteria.add(Restrictions.like(searchField, "%" + searchString + "%"));
//                }
//            }

////            Handle branch and usertype session
////             1 = President, 13 = Adminstrator
//            if (ut.getUsertypeid() != 1 && ut.getUsertypeid() != 13) {
//                //GET THE BRANCH SET UPON LOGIN in LINE 71 in LoginAuthentication.java
//                Branches branch = (Branches) ServletActionContext.getRequest().getSession().getAttribute("branch");
//                Employees emp = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
//                logger.info("branch: " + branch.getBranchcode());
//                if (branch.getBranchcode().equals("HO")) {//if Head Office..
//                    //Set grid to show only loanapps in that branch 
//                    //This code is equivalent to "from Loanapplications l inner join l.branches b where b.branchcode=:branchcode"
//                    //If you look at line 69 - 79 of this file you can see that I joined the foreign keyed tables already...
//                    
//                    criteria.add(Restrictions.eq("status", "posted"));
//                } else {
////                    criteria.add(Restrictions.eq("b.branchcode", branch.getBranchcode()));
//                    criteria.add(Restrictions.eq("e.idnumber", emp.getIdnumber()));
//                    criteria.add(Restrictions.eq("status", "pending"));
//                }
//            }
            
            criteria.add(Restrictions.eq("status", "saved")) ;
            // count loanapp
            records = loanappdao.countByCriteria(criteria);

            // reset count Projection, note: projection when incremented will set entry point for database,
            // so we need to reset it after counting all records.
            criteria.setProjection(null);
            criteria.setResultTransformer(Criteria.ROOT_ENTITY);

            // handle Order By
//            if (sidx != null && !sidx.equals("")) {
//                if (sidx.equals("borrowercode")) {
//                    if (sord.equals("asc")) {
//                        criteria.addOrder(Order.asc("boBra.branchcode")).addOrder(Order.asc("bo.borrowerid"));
//                    } else {
//                        criteria.addOrder(Order.desc("boBra.branchcode")).addOrder(Order.desc("bo.borrowerid"));
//                    }
//                } else {
//                    if (sidx.equals("area")) {
//                        sidx = "boAr.areacode";
//                    } else if (sidx.equals("borrowername")) {
//                        sidx = "bo.completename";
//                    } else if (sidx.equals("documentno")) {
//                        sidx = "d.documentno";
//                    } else if (sidx.equals("requestDocumentNo")) {
//                        if (!requestJoined) {
//                            criteria.createCriteria("request").createCriteria("documents", "reqDoc").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
//                        }
//                        sidx = "reqDoc.documentno";
//                    } else if (sidx.equals("idnumber")) {
//                        sidx = "e.idnumber";
//                    }
//
//                    if (sord.equals("asc")) {
//                        criteria.addOrder(Order.asc(sidx));
//                    } else {
//                        criteria.addOrder(Order.desc(sidx));
//                    }
//                }
//            }

            //et to = max rows
            if (to > records) {
                to = records;
            }

            // get all employees by criteria
            gridModel = loanappdao.findByCriteria(criteria, from, to);

            //total pages
            total = (int) Math.ceil((double) records / (double) rows);
        } catch (Exception e) {
            //catch whichever exception, get the current session info of the employee and log it.
//            Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
//            if (emps != null) {
//                logger.fatal("(" + emps.getIdnumber() + "):" + e.getLocalizedMessage(), e);
//            } else {
//                logger.fatal(e.getLocalizedMessage(), e);
//            }
//            e.printStackTrace();
//            //add action errors this will correspond to <s:actionerror/> in a struts-enabled jsp page.
//            addActionError(e.getLocalizedMessage());

            //if error then chain result to messages.jsp, which will display errors/messages.
            return ERROR;
        }
        return SUCCESS;
    }

    public String getJSON() {
        return execute();
    }

    public List<Loanverification> getGridModel() {
        return gridModel;
    }

    public void setGridModel(List<Loanverification> gridModel) {
        this.gridModel = gridModel;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRecords() {
        return records;
    }

    public void setRecords(Integer records) {
        this.records = records;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

    public String getSearchField() {
        return searchField;
    }

    public void setSearchField(String searchField) {
        this.searchField = searchField;
    }

    public String getSearchOper() {
        return searchOper;
    }

    public void setSearchOper(String searchOper) {
        this.searchOper = searchOper;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public String getSidx() {
        return sidx;
    }

    public void setSidx(String sidx) {
        this.sidx = sidx;
    }

    public String getSord() {
        return sord;
    }

    public void setSord(String sord) {
        this.sord = sord;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }
}
